#pragma once

#include "strategy/optimized_strategy_base.h"
#include <cmath>

namespace hft {

/**
 * @brief 优化的趋势跟踪策略
 * 
 * 使用RingBuffer优化的趋势跟踪策略，通过计算短期和长期移动平均线
 * 来识别和跟踪市场趋势。相比原始版本，具有更好的性能和内存使用效率。
 */
class OptimizedTrendFollowingStrategy : public OptimizedStrategyBase {
public:
    OptimizedTrendFollowingStrategy(
        const std::string& symbol,
        size_t short_period = 10,
        size_t long_period = 30,
        double trend_threshold = 0.001  // 0.1%的趋势确认阈值
    )
        : OptimizedStrategyBase("OptimizedTrendFollowing", std::max(short_period, long_period))
        , symbol_(symbol)
        , short_period_(short_period)
        , long_period_(long_period)
        , trend_threshold_(trend_threshold)
        , position_(0)
        , last_trend_direction_(0) {}

    bool init(const std::string& config) override {
        // 可以从配置中读取参数
        running_ = true;
        return true;
    }

    bool start() override {
        if (!running_) {
            running_ = true;
            price_manager_.clear(symbol_);  // 清除历史数据，重新开始
            position_ = 0;
            last_trend_direction_ = 0;
        }
        return true;
    }

    void stop() override {
        running_ = false;
    }

    void onMarketData(const MarketData& data) override {
        if (!running_ || data.symbol != symbol_) {
            return;
        }

        // 更新价格历史
        price_manager_.addPrice(symbol_, data.close);

        // 确保有足够的历史数据
        if (!price_manager_.hasEnoughHistory(symbol_, long_period_)) {
            return;
        }

        // 计算短期和长期移动平均线
        double short_ma = price_manager_.getMA(symbol_, short_period_);
        double long_ma = price_manager_.getMA(symbol_, long_period_);

        // 计算趋势强度
        double trend_strength = (short_ma - long_ma) / long_ma;
        int current_trend = 0;

        if (std::abs(trend_strength) > trend_threshold_) {
            current_trend = trend_strength > 0 ? 1 : -1;
        }

        // 生成交易信号
        if (current_trend != 0 && current_trend != last_trend_direction_) {
            Signal signal;
            signal.symbol = symbol_;
            signal.timestamp = std::chrono::system_clock::now();
            signal.price = data.close;

            if (current_trend > 0) {  // 上升趋势
                if (position_ <= 0) {  // 如果当前空仓或空头
                    signal.type = Signal::Type::BUY;
                    signal.quantity = 1 + std::abs(position_);  // 平空+做多
                    position_ = 1;
                    executeSignal(signal);
                }
            }
            else {  // 下降趋势
                if (position_ >= 0) {  // 如果当前空仓或多头
                    signal.type = Signal::Type::SELL;
                    signal.quantity = 1 + position_;  // 平多+做空
                    position_ = -1;
                    executeSignal(signal);
                }
            }

            last_trend_direction_ = current_trend;
        }
        // 趋势消失，平仓
        else if (current_trend == 0 && last_trend_direction_ != 0) {
            if (position_ != 0) {
                Signal signal;
                signal.symbol = symbol_;
                signal.timestamp = std::chrono::system_clock::now();
                signal.price = data.close;
                signal.type = position_ > 0 ? Signal::Type::SELL : Signal::Type::BUY;
                signal.quantity = std::abs(position_);
                position_ = 0;
                executeSignal(signal);
            }
            last_trend_direction_ = 0;
        }
    }

    void onOrderBookUpdate(const OrderBook& orderBook) override {
        // 可以添加订单簿分析逻辑来优化入场点
    }

    void onOrderUpdate(const Order& order) override {
        // 处理订单状态更新
    }

    void onOrderFilled(const Trade& trade) override {
        // 处理订单成交
    }

    void onOrderCancelled(const Order& order) override {
        // 处理订单取消
    }

    std::string getName() const override { return "OptimizedTrendFollowingStrategy"; }
    std::string getStatus() const override { return running_ ? "RUNNING" : "STOPPED"; }
    int getStrategyId() const override { return 7; }

private:
    std::string symbol_;
    size_t short_period_;
    size_t long_period_;
    double trend_threshold_;
    int position_;  // 1: 多头, -1: 空头, 0: 空仓
    int last_trend_direction_;  // 1: 上升, -1: 下降, 0: 无趋势
    bool running_{false};

    // 执行交易信号
    void executeSignal(const Signal& signal) {
        Order order;
        order.symbol = signal.symbol;
        order.price = signal.price;
        order.quantity = signal.quantity;
        order.direction = (signal.type == Signal::Type::BUY) ? 
            OrderDirection::BUY : OrderDirection::SELL;
        order.offset = OrderOffset::OPEN;  // 简化处理，实际应该根据持仓情况决定
        
        sendOrder(order);
    }

    std::string sendOrder(const Order& order) override {
        // 实现订单发送逻辑
        if (trading_system_) {
            // 通过交易系统发送订单
            return "order_id";  // 实际应返回真实的订单ID
        }
        return "";
    }
};

} // namespace hft